<!--btns-wrapper
 * @Descripttion: 计划管理->主生产计划
 * @version: V1.0
 * @Author: GaoWei
 * @Date: 2021-04-25 12:11:55
 * @LastEditors: GW
 * @LastEditTime: 2021-12-20 14:06:53
-->

<template>
    <div class="content-wrapper a-base-container">
        <div class="requisition-set-wrapper" style="display:block">
            <!-- 按钮 -->
            <div class="btn-wrapper clearfix">
                <btns-wrapper @searchClick="searchClick" :showModel="showModel" :orderId="orderId" :num="num" :voucherState="voucherState" :editMask="editMask" @printOrder="printOrder" @switchList="switchList" @submitServer="submitServer" @clickEdit="clickEdit" @deleteOrder="deleteOrder" @getIdByData="getIdByData" @auditClick="auditClick" @turnThePage="turnThePage" @syncOrder="syncOrder" @submitOrder="submitOrder" @exportDetail="exportDetail" :sourceCode="sourceCode">
                    <template slot="neworder">
                        <a-dropdown class="btns" key="new" style="display:block">
                            <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">新增
                                    <a-icon type="down" style="color:rgb(24,144,255);vertical-align:middle;" />
                                </div>
                            </a>
                            <a-menu slot="overlay">
                                <a-menu-item key="0">
                                    <a href="javascript:void(0)" @click="newForecast">新增</a>
                                </a-menu-item>
                                <a-menu-item key="1">
                                    <a href="javascript:void(0)" @click="choiceBillsFromSaleOrder">选销售订单</a>
                                </a-menu-item>
                            </a-menu>
                        </a-dropdown>
                    </template>
                    <!-- <template slot="hebing">
                        <a-dropdown class="btns" key="new" style="display:block">
                            <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">合并
                                    <a-icon type="down" style="color:rgb(24,144,255);vertical-align:middle;" />
                                </div>
                            </a>
                            <a-menu slot="overlay">
                                <a-menu-item key="0">
                                    <a href="javascript:void(0)" @click="newForecast">合并</a>
                                </a-menu-item>
                                <a-menu-item key="1">
                                    <a href="javascript:void(0)" @click="choiceBillsFromSaleOrder">拆分</a>
                                </a-menu-item>
                            </a-menu>
                        </a-dropdown>
                    </template> -->
                    <template slot="guanbi">
                        <a-dropdown class="btns" key="sheng" style="display:block">
                            <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                                <a-icon class="btns-icon" type="snippets" />
                                <div class="btns-text">关闭
                                    <a-icon type="down" />
                                </div>
                            </a>
                            <!-- <a-menu v-if="voucherState==1" slot="overlay"> -->
                            <a-menu slot="overlay">
                                <a-menu-item key="0">
                                    <a href="javascript:void(0)" @click="getclosed(1)">打开</a>
                                </a-menu-item>
                                <a-menu-item key="1">
                                    <a href="javascript:void(0)" @click="getclosed(10)">关闭</a>
                                </a-menu-item>
                            </a-menu>
                        </a-dropdown>
                    </template>

                    <template slot="shengdan">
                        <a-dropdown class="btns" key="sheng" style="display:block">
                            <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                                <a-icon class="btns-icon" type="snippets" />
                                <div class="btns-text">下达
                                    <a-icon type="down" />
                                </div>
                            </a>
                            <!-- <a-menu v-if="voucherState==1" slot="overlay"> -->
                            <a-menu slot="overlay">
                                <template v-if="[-1,0].includes(voucherState)">
                                    <a-menu-item key="0">
                                        <a href="javascript:void(0)">
                                            <span :class="'color-gray'">下达生产</span>
                                        </a>
                                    </a-menu-item>
                                    <a-menu-item key="1">
                                        <a href="javascript:void(0)">
                                            <span :class="'color-gray'">下达委外</span>
                                        </a>
                                    </a-menu-item>
                                    <a-menu-item key="2">
                                        <a href="javascript:void(0)" >
                                             <span :class="'color-gray'">下达请购</span>
                                        </a>
                                    </a-menu-item>
                                </template>
                                <template v-else>
                                    <a-menu-item key="0" v-show ='num==2?true:false'>
                                        <a href="javascript:void(0)"  @click="generateBills('ReleaseProduction',0,listArr)">下达生产</a>
                                    </a-menu-item>
                                    <a-menu-item key="1" v-show ='num==3?true:false'>
                                        <a href="javascript:void(0)"  @click="generateBills('AssignOutsourcing',1,listArr)">下达委外</a>
                                    </a-menu-item>
                                    <a-menu-item key="2" v-show ='num==1?true:false'>
                                        <a href="javascript:void(0)"  @click="generateBills('ReleaseProcurement',2,listArr)">下达请购</a>
                                    </a-menu-item>
                                </template>
                            </a-menu>
                        </a-dropdown>
                    </template>
                    <template slot="moreBtn">
                         <a-col class="btn-item" :class="[-1,0].includes(voucherState) ? 'btns-disable':''">
                            <a-dropdown class="btns" key="sheng" style="display:block">
                                <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                                    <a-icon class="btns-icon" type="snippets" />
                                    <div class="btns-text">合拆
                                        <a-icon type="down" />
                                    </div>
                                </a>
                                <!-- <a-menu v-if="voucherState==1" slot="overlay"> -->
                                <a-menu slot="overlay">
                                    <template v-if="[-1,0].includes(voucherState)">
                                        <a-menu-item key="0">
                                            <a href="javascript:void(0)" >
                                              <span :class="'color-gray'">合并</span>
                                            </a>
                                        </a-menu-item>
                                        <a-menu-item key="1">
                                            <a href="javascript:void(0)">
                                              <span :class="'color-gray'">拆分</span>
                                            </a>
                                        </a-menu-item>
                                    </template>
                                    <template v-else>
                                        <a-menu-item key="0">
                                            <a href="javascript:void(0)" @click="merge">
                                                <span>合并</span>
                                            </a>
                                        </a-menu-item>
                                        <a-menu-item key="1">
                                            <a href="javascript:void(0)" @click="split">
                                                <span>拆分</span>
                                            </a>
                                        </a-menu-item>
                                    </template>
                                </a-menu>
                            </a-dropdown>
                         </a-col>
                    </template>
                    <!-- <template slot="hebing">
                        <div class="btns" @click="merge">
                            <a-icon class="btns-icon" type="edit" />
                            <div class="btns-text">合并</div>
                        </div>
                        
                    </template>
                    <template slot="chaifen">
                        <div class="btns" @click="split">
                    <a-icon class="btns-icon" type="edit" />
                    <div class="btns-text">拆分</div>
                </div>
                
                    </template> -->
                </btns-wrapper>
            </div>
            <div ref="print" class="documents-wrapper" id="documents-wrapper">
                <h3 class="text-center">
                    {{voucherTitle}}
                </h3>
                <section v-show="showModel=='list'">
                    <!--列表-->
                    <dynamicList ref="dyList" :basePostData="basePostData" :sourceCode="sourceCode" @switchList="switchList" @dblclick="getIdByData" :reportCode="reportCodeList"></dynamicList>
                </section>
                <section v-show="showModel=='order'">
                    <!-- <div>
                        <span class="audit-status" v-show="voucherState==0 && closedState == 1">待审核</span>
                        <span class="audit-status" v-show="(voucherState==1 || voucherState==10) && closedState == 1">
                            <span>已审核</span>
                        </span>
                        <span class="audit-status" v-show="closedState == 0">关闭</span>
                    </div> -->

                    <div>
                        <span class="audit-status" v-show="voucherState==0">待审核</span>
                        <span class="audit-status" v-show="voucherState==1 || voucherState==10">{{voucherState==1?'已审核':'关闭'}}</span>
                    </div>

                    <a-form-model :layout="formLayout">
                        <div class="header-box">
                            <order-dynamic-form :FormData="orderHeaderData" @changetime="onChangeTime" @clickItem="setValue"></order-dynamic-form>
                            <div class="edit-mask-header" v-show="editMask">
                                <!-- 遮罩（点击修改关闭遮罩） -->
                            </div>
                        </div>
                        <div class="table-box">
                            
                            <a-table :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" id="bills_tb" :columns="columns" :data-source="dataSource" :customRow="customClick" :scroll="{ x: 1000, y: 347 }" :pagination="false" @change="onTableChange" :size="small" bordered>
                                <template slot="number" v-if="isRouterAlive" slot-scope="text, record, index">
                                    <div v-if="index == dataSource.length-1">
                                        合计
                                    </div>
                                    <div v-else>
                                        {{index+1}}
                                    </div>
                                </template>
                                <template v-for="col in slotArray" :slot="col" slot-scope="text, record,index">
                                    <div data-key="">
                                        <editable-cell v-if="isRouterAlive" :checkType="checkType" :text="text" :col="col" :index="index" :record="record" :dataSource="dataSource" :unitsDataDetails="unitsDataDetails" :unitsAssistSelect="unitsAssistSelect" :dynamicAllData="dynamicFormData" :dynamicFormDataMap="dynamicFormDataMap"  @choiceAddData="choiceAddData(index,item,$event,'plan')" @change="onCellChange(index, col, $event)" @newAddData="handleAdd" />
                                    </div>
                                </template>
                            </a-table>
                            <div class="edit-mask edit-mask-selection" v-show="editMask">
                                <!-- 遮罩（点击修改关闭遮罩） -->
                            </div>
                        </div>
                        <div class="footer-box">
                            <order-dynamic-form :FormData="orderFooterData" @downSelectChange="downSelectChange"  @changetime="onChangeTime" @clickItem="setValue"></order-dynamic-form>
                            <div class="edit-mask-footer" v-show="editMask">
                                <!-- 遮罩（点击修改关闭遮罩） -->
                            </div>
                        </div>
                    </a-form-model>

                </section>
                <section v-show="showModel=='detail'">
                    <!--明细-->
                    <dynamicListDetails ref="detailSearchRef" :reportCode="reportCodeDetail" :componentType="1" :basePostData="basePostData"></dynamicListDetails>
                </section>
                <section v-show="showModel=='statistical'">
                    <!--统计-->
                    <dynamicListDetails ref="statisticalSearchRef" :reportCode="reportCodeStatistical" :componentType="2" :basePostData="basePostData"></dynamicListDetails>
                </section>
            </div>
            <div class="contextmenu-box">
                <!-- 右键菜单 -->
                <ul v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
                    <li @click="handleAdd()">新增行</li>
                    <li @click="handleDelete()">删除行</li>
                    <!-- <li @click="handleCopy()">复制行</li> -->
                </ul>
            </div>
            <drawerBox ref="searchList" :unitData="unitData" :unitsData="unitsData" :unitsDataDetails="unitsDataDetails" :productionPlanToSalesOrder="productionPlanToSalesOrder" @editClickOrder="editClickOrder"></drawerBox>
        </div>

        <!--加载中-->
        <div class="loading-wrapper" v-show="loading">
            <a-spin class="loading-content" tip="加载中..." />
        </div>
        <!--用做横向打印-->
        <!-- <div v-html="stylePrint"></div> -->
        <print-modal ref="printDom" v-if="printVisible" :incomingPrintData="incomingPrintData" @cancelPrint="cancelPrint"></print-modal>

        <!--生产订单分单-->
        <production-orders-modal ref="productionOrderRef" :propsData="propsData"></production-orders-modal>
        <!-- 拆分物料 -->
        <split-material v-if="visibleSplit" ref="splitmaterial" :splitData="splitData" :data-source="dataSource" @close="close" @splitSubmit="splitSubmit"></split-material>
    </div>
</template>
<script>


import { save, examine, remove, getCode, submitOrder,setMerge,setSplit,closed } from '@/api/production/productionPlan'
import pro from '@/mixins/procurement/pro'
//import productionOrdersModal from '@/components/SeparateBill/productionOrdersModal.vue';
import drawerBox from './drawerBox.vue';
import getDate from "@/utils/tool/date";
import AgForm from '../../components/AgForm/AgForm.vue';
import splitMaterial from './splitMaterial.vue'
import { _ } from "core-js";
import path from 'path';
export default {
    //productionOrdersModal
    components: { drawerBox, AgForm ,splitMaterial},
    mixins: [pro],
    data () {
        return {
            sourceCode: 'MasterProductionSchedule',
            reportCodeDetail: 'ProductionPlan_Detail_Report',
            reportCodeStatistical: 'ProductionPlan_Statistic_Report',   //统计code
            reportCodeList: 'ProductionPlan_List_Report',              //列表code

            checkType: 'is_made_self,is_made_request',//采购，生产，委外
            productionPlanToSalesOrder: true,//标识：是主生产计划选销售订单
            selectedRowKeys: [],
            selectedRowKeysList: [],
            visibleSplit:false,
            splitData:'',
            listArr:[],//选中获取的数据
            num:0,//判断下达是否可以点击
        };
    },
    mounted () {
        //this.getIdByData();//获取最新一条数据
    },
    activated(){
        //this.getIdByData();
        //console.log(this.orderHeaderData);
    },
    methods: {
        // editClickOrder(record, index){
        //     console.log(record, index);
        // },
        close(value) {
            this.visibleSplit = value
        },
        getclosed(type){
            let data = {
                id: this.orderId,
                status: type,
            }
            closed(data).then(res => {
                console.log(res);
                if (res.code === 200) {
                    this.$message.success('操作成功');
                    this.editMask = true;
                    this.isSaveRun = true;
                    this.getIdByData(); //获取最新一条数据
                } else {
                    this.$message.error(response.message);
                    this.isSaveRun = true;
                }
            })
        },
        split() {
            console.log(this.selectedRowKeysList)
            if(this.selectedRowKeysList.length==0){
                this.$message.warning('请选择拆分的物料')
                return
            }
            if(this.selectedRowKeysList.length>1){
                this.$message.warning ('只能选择一种物料拆分')
                return
            }
            this.visibleSplit = !this.visibleSplit
            this.splitData = this.selectedRowKeysList[0]
            // this.dataSource.forEach(item=>{
            //     if(item.bussessPlan==this.selectedRowKeysList[1]){
            //         this.splitData=item
            //     }
            // })
        },
        merge() {
            if(this.selectedRowKeysList.length < 2){
                this.$message.warning('请至少选择2条物料合并!')
                return
            }
            let arr = []
            arr = this.selectedRowKeysList.map(item => {
                return item.inventoryCode
            })
            if ([...new Set(arr)].length > 1) {
                this.$message.warning('不同物料，不能合并！')
                return
            }

            let data = this.formatDataSource(this.selectedRowKeysList)
            setMerge(data).then(res => {
                if (res.code === 200) {
                    this.$message.success('合并成功');
                    this.getIdByData();
                    this.selectedRowKeysList = [];
                    this.selectedRowKeys = [];
                }
            })
            // setMerge
        },
        // 判断点击的是哪一个生成订单能够触发
        isTrueFn(rows){
            this.num=rows[0].bussessPlanId;
        },
        onSelectChange(selectedRowKeys,rows) {
            this.listArr=rows;
            // if(rows[0].bussessPlanId)
            if(rows.length>0){
                this.isTrueFn(rows)
            }
            let PlanId1 = []
            let PlanId2 = []
            let PlanId3 = []
            for (let index = 0; index < rows.length; index++) {
                if(rows[index].bussessPlanId == 1){//采购
                    PlanId1.push(rows[index].bussessPlanId)
                }
                if(rows[index].bussessPlanId == 2){//自制
                    PlanId2.push(rows[index].bussessPlanId)
                }
                if(rows[index].bussessPlanId == 3){//委外
                    PlanId3.push(rows[index].bussessPlanId)
                }
            }
            if(PlanId1.length != rows.length || PlanId1.PlanId2 != rows.length || PlanId3.length != rows.length){
                this.num = 0;
            }

            if(PlanId1.length && PlanId1.length == rows.length){
                this.num = 1;
            }
            if(PlanId2.length && PlanId2.length == rows.length){
                this.num = 2;
            }
            if(PlanId3.length && PlanId3.length == rows.length){
                this.num = 3;
            }

            //下达生产2  下达委外3 下达请购1

            let arr = []
            this.selectedRowKeysList=[]
            this.selectedRowKeys = [...selectedRowKeys]
            // this.dataSource.forEach(item => {
            //     if(selectedRowKeys.map(item=>{return item+1}).indexOf(item.bussessPlanId)!==-1){
            //         arr.push(item)
            //     }
            // })
            // this.selectedRowKeysList = arr
            this.dataSource.forEach(i => {
                rows.forEach(j => {
                    if (i.id === j.id) {
                        arr.push(i)
                    }
                })
            })
            this.selectedRowKeysList = [...new Set(arr)]
        },
        //新增预测单
        newForecast () {
            this.showModel = 'order';
            this.editMask = false;
            this.loading = false;
            this.voucherState = -1;
            this.sourceVoucherData = {};//清空来源数据
            this.initForm(1);
        },
        //保存
        submit (requestData) {
            requestData.createUserId = this.$store.state.user.info.id
            requestData.createUserName = this.$store.state.user.info.name
            requestData.dataSource = "MasterProductionSchedule"
            save(requestData).then(response => {
                if (response.code === 200) {
                    this.$message.success('保存成功');
                    this.editMask = true;
                    this.isSaveRun = true;
                    if (!this.orderId) {
                        this.getIdByData(); //获取最新一条数据
                    }
                } else {
                    this.$message.error(response.message);
                    this.isSaveRun = true;
                }
            }).catch((e) => {
                this.isSaveRun = true;
            })
        },
        splitSubmit(list) {
            let data = this.formatDataSource(list)
            setSplit(data).then(res => {
                if (res.code === 200) {
                    this.$message.success('拆分成功');
                    this.getIdByData();
                    this.$refs.splitmaterial.close()
                    this.selectedRowKeysList = [];
                    this.selectedRowKeys = [];
                }
            })
        },
        //单据提交
        submitOrder (type) {
            let data = {
                id: this.orderId,
                status: type,//状态 -1:撤回提交,0:提交
            }
            console.log(this.orderId);
            if (!this.orderId) {
                this.$message.warning('该单据未保存不需要提交');
                return;
            }
            if (this.voucherState == -1 && type == -1) {
                this.$message.warning('该单据未提交无需撤回提交');
                return;
            }
            submitOrder(data).then(res => {
                if (res.code === 200) {
                    if (type == 0) {
                        this.$message.success('提交成功');
                    } else {
                        this.$message.success('撤回提交成功');
                    }
                    this.getIdByData();
                }
            })
        },
        //审核
        auditClick (type) {
            let requestData = {
                id: this.orderId,
                status: type
            }
            examine(requestData).then((response) => {
                if (response.code === 200) {
                    const backData = response.data;
                    if (type == 1) {
                        this.$message.success('审核成功');
                        this.getIdByData();
                    }
                    if (type == 0) {
                        this.$message.success('弃审成功');
                        this.getIdByData();
                    }
                } else {
                    // this.$message.warning(response.message);
                }
            })
        },
        //删除
        remove (postData) {
            remove(postData).then(response => {
                if (response.code === 200) {
                    this.$message.success('删除成功');
                    this.orderId = '';
                    this.voucherState = 0;
                    this.getIdByData();//获取最新一条数据
                } else {
                    this.$message.error(response.message);
                }
            })
        },
        //获取单据编号
        getCode () {
            console.log(1);
            getCode().then((res) => {
                if (res.code == 200) {
                    this.receiptNumber = res.message;
                    console.log(this.orderHeaderData)
                    for (let i = 0; i < this.orderHeaderData.length; i++) {
                        if (this.orderHeaderData[i].code == 'voucherCode') {
                            this.$set(this.orderHeaderData[i], 'onEdit', false)
                            this.$set(this.orderHeaderData[i], 'value', this.receiptNumber)
                        }
                        if (this.orderHeaderData[i].code == 'voucherDate') {
                            this.$set(this.orderHeaderData[i], 'value', getDate.getCurrentMoment().format('YYYY-MM-DD'))
                        }
                    }
                } else {
                    // this.$message.warning(res.message);
                }
            });
        },
        //选销售订单
        choiceBillsFromSaleOrder () {
            let postData = {
                sourceCode: 'SaleOrder',      // 来源单
                title: '选销售订单',
                businessType: 5, //1:退货业务 2：非退货业务 3: 退货 + 非退货 4: 发票 5.销售订单 未生产 主计划单
                someBusinessType: "0",    // 指定业务类型 默认 0
                startVoucherState: 0,
                endVoucherState: 10
            }
            for (let i = 0; i < this.orderHeaderData.length; i++) {
                if (this.orderHeaderData[i].code == 'createdType') {
                    this.$set(this.orderHeaderData[i], 'value', 0)
                }
            }
            this.$refs.searchList.onOpenBox(postData);
        },
    }
};
</script>
<style lang="less" scoped>
    @import '~@/style/purchase/voucher.less';
    .requisition-set-wrapper .edit-mask-selection {
        width:calc(100% - 60px);
        left:60px;
    }
</style>